import sys
import ply.yacc as yacc
from lex import tokens


fout = None

def p_program(p):
	'''program	: program stmt
				| stmt
				'''

def p_stmt(p):
	'''stmt	: expr '''
	p[0] = p[1]
	print(p[0], file=fout)
	p[0] = None

def p_stmt_assign(p):
	'stmt : ID ASSIGN expr'
	p[0] = p[1] + " = " + p[3]
	print(p[0], file=fout)
	p[0] = ''


def p_stmt_input(p):
	'''stmt : INPUT EXPORT input_param_list'''
	p[0] = "\n".join(p[3])
	print(p[0], file=fout)
	p[0] = ''

def p_input_param_list(p):
	'''input_param_list : input_param_list COMMA input_param
						| input_param
						'''
	if len(p) == 2:
		p[0] = [p[1]]
	else:
		p[0] = p[1]
		p[0].append(p[3])

def p_input_param(p):
	'input_param : ID LB NUMBER COMMA NUMBER COMMA NUMBER COMMA NUMBER RB'
	p[0] = "%s = MAKE_INPUT(%s, %s, %s, %s)" % (p[1], p[3], p[5], p[7], p[9])
	
def p_stmt_export(p):
	'''stmt : ID EXPORT expr
			| ID EXPORT expr COMMA ID'''
	if len(p) == 4:
		p[0] = 'EXPORT("%s", %s, "%s")' % ( p[1], p[3], "" )
	elif len(p) == 6:
		p[0] = 'EXPORT("%s", %s, "%s")' % ( p[1], p[3], p[5] )
	print(p[0], file=fout)
	p[0] = ''

def p_expr_binary(p):
	'''expr : expr PLUS expr
			| expr MINUS expr
			| expr TIMES expr
			| expr DIVIDE expr
			| expr GREATER expr
			'''
	p[0] = "%s %s %s" % (p[1], p[2], p[3])

def p_expr_lbrb(p):
	'expr : LB expr RB'
	p[0] = '(' + p[2] + ')'

def p_expr_func(p):
	'expr : ID LB func_param_list RB'
	p[0] = p[1] + '(' + p[3] + ')'


def p_func_param_list(p):
	'''func_param_list : func_param_list COMMA expr 
					   | expr'''
	if len(p) == 2:
		p[0] = p[1]
	elif len(p) == 4:
		p[0] = p[1]
		p[0] += "," + p[3]
		

def p_expr(p):
	'''expr : NUMBER
			| ID
			'''
	p[0] = str(p[1])

def p_expr_var(p):
	'''expr : VAR '''
	p[0] = 'STOCK_DATA(CODE,PERIOD,"%s")' % p[1]


if len(sys.argv) > 1:
	data = open(sys.argv[1]).read()
	fout = open(sys.argv[1] + ".lua", "w")
	parser = yacc.yacc()
	parser.parse(data)
	fout.close()
